package mirrormonkey.samples.netbricks.server;

import java.util.Map;

import mirrormonkey.core.module.CoreModule;
import mirrormonkey.core.server.ServerCoreModule;
import mirrormonkey.framework.ServerSyncAppState;
import mirrormonkey.rpc.module.RpcModule;
import mirrormonkey.samples.netbricks.entities.Brick;
import mirrormonkey.samples.netbricks.entities.Floor;
import mirrormonkey.samples.netbricks.entities.ServerBrick;
import mirrormonkey.samples.netbricks.entities.ServerPlayerCharacter;
import mirrormonkey.state.module.StateUpdateModule;

import com.jme3.app.SimpleApplication;
import com.jme3.network.ConnectionListener;
import com.jme3.network.HostedConnection;
import com.jme3.network.Network;
import com.jme3.network.Server;
import com.jme3.system.JmeContext;

public class ServerApplication extends SimpleApplication {

	public static final int PORT = 20480;

	private ServerSyncAppState syncAppState;

	private ServerBrick[] bricks;

	private Floor floor;

	private Map<Integer, ServerPlayerCharacter> playerCharacters;

	@Override
	public void simpleInitApp() {
		Server server;
		try {
			server = Network.createServer(PORT);
			syncAppState = new ServerSyncAppState(server);

			CoreModule module = syncAppState.getModule(CoreModule.class);
			syncAppState.getModule(RpcModule.class);
			syncAppState.getModule(StateUpdateModule.class);

			syncAppState.eventManager
					.addConnectionListener(new ClientConnectionListener());

			server.start();
		} catch (Throwable e) {
			throw new RuntimeException(e);
		}
	}

	public final class ClientConnectionListener implements ConnectionListener {

		@Override
		public void connectionAdded(Server server, HostedConnection conn) {
			ServerCoreModule mod = syncAppState
					.getModule(ServerCoreModule.class);
			mod.addMapping(conn, floor, Floor.class);
			for (ServerBrick e : bricks) {
				mod.addMapping(conn, e, Brick.class);
			}
			for (ServerPlayerCharacter pc : playerCharacters.values()) {
				mod.addMapping(conn, floor, Floor.class);
			}
		}

		@Override
		public void connectionRemoved(Server server, HostedConnection conn) {

		}

	}

	public static void main(String[] args) {
		ServerApplication app = new ServerApplication();
		app.start(JmeContext.Type.Headless);
	}

}
